package com.east.sng.config;

import com.east.sng.entity.result.UserFind;
import com.east.sng.service.RoleService;
import com.east.sng.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;

/**
 * @author east
 * @date: 2021/1/4
 * @Description: custom user data interaction realm
 **/
public class UserRealm extends AuthorizingRealm {
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;

    @Override
    public String getName(){
        return "UserRealm";
    }

    /**
     * 授权操作
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取当前授权用户
        UserFind u = (UserFind) principalCollection.getPrimaryPrincipal();
        //根据用户的角色序列号查询角色代码
        String roleCode = roleService.findRoleCode(u.getRoleId());
        //判断角色是否为管理员
        List<String> permission = new ArrayList<>();
        if ("0".equals(roleCode)) {
            //管理员则分配全部取消
            permission.add("*:*");
        } else {
            //根据角色序列号查询用户权限
            permission = roleService.findMenuCodes(u.getRoleId());
        }
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.addRole(roleCode);
        authorizationInfo.addStringPermissions(permission);
        return authorizationInfo;
    }

    /**
     * 认证操作
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //防止Post请求先认证
        if (authenticationToken.getPrincipal() == null) {
            return null;
        }
        //获取token
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        //根据用户名查询用户信息
        UserFind u = userService.findUser(token.getUsername());
        //用户不存在时
        if (u == null) {
            return null;
        }
        //shiro验证用户密码
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(u, u.getUserPassword(), ByteSource.Util.bytes(u.getSalt()), getName());
        //保存用户名到session中
        Session session = SecurityUtils.getSubject().getSession();
        session.setAttribute("username",u.getUserName());
        return info;
    }

}
